#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QDebug>
#include <QScopedPointer>

#include <stdlib.h>
#include <vector>

#include "PKEncrypter.h"
#include "PublicKey.h"
#include "KeyManager.h"
#include "KeyGenerator.h"

using namespace kryptos::cryptography;
using namespace kryptos::entities;

class PublicKeyEncryptionTest : public QObject
{
    Q_OBJECT

public:
    PublicKeyEncryptionTest(){}
    ~PublicKeyEncryptionTest(){}

private Q_SLOTS:

    void initTestCase();
    void cleanupTestCase();

    void encryptBuffer();
    void decryptBuffer();

private:
    QScopedPointer<PrivateKey> privkey;
    std::string testinput;
    std::vector<char> cifrado, descifrado;

};

void PublicKeyEncryptionTest::initTestCase()
{
    KeyGenerator::init();

    KeyInfo info(KeyInfo::RSA, "sebastian", "seba@mail.com", "test", "sebastian", 1024);
    privkey.reset(new PrivateKey(KeyGenerator::generateKey(info, info.type())));

    // Comment the above key generation nd Uncomment the line below, to test with a key loaded from the database
    //privkey.reset(new PrivateKey(KeyManager::instance().findKey("superpacko@gmail.com", "sebastian")));

    testinput = "Probando encrypcion asymetrica de texto";
}

void PublicKeyEncryptionTest::cleanupTestCase()
{
}

void PublicKeyEncryptionTest::encryptBuffer()
{
    PKEncrypter encrypter(privkey->publicKeyPart());

    int result = encrypter.encryptBuffer(testinput.c_str(), testinput.size(), cifrado);
    QVERIFY2(result == 0, "Error encrypting");
}

void PublicKeyEncryptionTest::decryptBuffer()
{
    PKEncrypter decrypter(*privkey.data());

    decrypter.decryptBuffer(cifrado.data(), cifrado.size(), descifrado);

    std::string decrypted(descifrado.data(), descifrado.size());
    QVERIFY2(testinput == decrypted, "Error decrypting");
}


QTEST_MAIN(PublicKeyEncryptionTest);

#include "PublicKeyEncryptionTest.moc"
